/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package yinshi.cfg;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;

/**
 *
 * @author yinshi
 */
class GrammarBuilder {

    private String[] names;
    private Symbol[] expression;
    private Terminal[] terminals;
    //
    private final Form form;

    GrammarBuilder(Form form) {
        this.form = form;

        // Get the relation map of the form.
        Map<String, Symbol> map = form.getRelations();

        // Get the names of the non-terminal symbols.
        names = map.keySet().toArray(new String[0]);

        List<Symbol> symbols = new ArrayList();
        // Create a new list to store all the symbols.
        for (String name : names) {
            symbols.add(map.get(name));
        }
        expression = symbols.toArray(new Symbol[0]);

        terminals = form.getAllTerminals().toArray(new Terminal[0]);
    }

    private Grammar generate() {
        // Create a index list to store the index.
        List relations = new ArrayList();
        List<Integer> index = new ArrayList<>();

        for (int i = 0; i < expression.length; i++) {
            List list = new ArrayList();
            list.add(expression[i]);
            relations.add(list);
            index.add(i);
        }

        return null;
    }

    private void divideSymbol(List relations, List<Integer> index, int i) {
        if ((numOfNonTerminals <= i) && (i < numOfSymbols)) {
            return;
        }
        Symbol symbol = (Symbol) relations.get(i);
        if (symbol instanceof Terminal) {
            relations.set(i, null);
        } else {
            Group ntSymbol = (Group) symbol;
            int[] ts = new int[ntSymbol.symbols.length];
            for (int j = 0; j < ts.length; j++) {
                symbol = ntSymbol.symbols[j];
                if (symbol instanceof Terminal) {
                    ts[i] = findSymbol(relations, symbol);
                } else if (symbol instanceof Group) {
                    ts[i] = relations.size();
                    relations.add(symbol);
                }
            }
            relations.set(i, ts);
        }
    }

    private static int[] findSymbol(Stack symbols) {
        int[] ts = new int[symbols.size() + 1];
        for (int i = 1; i < symbols.size(); i++) {
            Arrays.
            
            
            
            
            if (symbols[i] == symbol) {
                return i;
            }
        }
        return -1;
    }
}
